#pragma once

#include <unordered_map>
#include <functional>
#include <iostream>
#include <unistd.h>
#include <time.h>
#include<stdlib.h>
using task_t = std::function<void()>;
static int number = 0;

void Print()
{
    std::cout << "打印任务... pid: " << getpid() << std::endl << std::endl;
}

void DownLoad()
{
    std::cout << "下载任务...pid: " << getpid() << std::endl<< std::endl;
}

void SQL()
{
    std::cout << "数据库任务...pid: " << getpid() << std::endl<< std::endl;
}

void Install()
{
    std::cout << "安装任务...pid: " << getpid() << std::endl<< std::endl;
}

class TaskManager
{
public:
    TaskManager()
    {
        srand(time(nullptr));
        this->Insert(Print);
        this->Insert(DownLoad);
        Insert(SQL);
        Insert(Install);
    }
    ~TaskManager()
    {
    }

    void Insert(task_t task)
    {
        tasks[number++] = task;
    }

    int Select()
    {
        return rand() % number;
    }

    void Execute(int num)
    {
        if (tasks.find(num) == tasks.end())
            return;
        tasks[num]();
    }

private:
    std::unordered_map<int, task_t> tasks;
};

TaskManager taskManeger;


void Work()
{
    while (true)
    {
        int task = 0;
        int n = read(0, &task, sizeof(task));
        if (n == 0)
        {
            cout << "child pid :" << getpid() << " quit success" << endl;
            break; // 写端关闭，读到了文件尾
        }
        else if (n == sizeof(task))
        {
            taskManeger.Execute(task);
        }
        else
        {
            // to dot
        }
    }
}
